﻿$(document).ready(function(){
    /*** 初始化 ***/
    //ajax请求时的加载状态
    $(window).ajaxSend(function(evt, request, settings){
        look.loader.show();
    }).ajaxComplete(function(event, request, settings){
        look.loader.hide();
        publicInit.i18n.Render();
    });
	
	$(window).resize(function(){
        publicInit.layout();
    });
    publicInit.layout();
	
    //监视hash
    try {
        $(window).hashchange(function(){
            look.loadFn();
        });
        $(window).hashchange();
    } catch (e) {
    }
});

var publicInit = {
    headerLoader: function(){
        if ($("#header").children().length == 0) {
            loadPage("#header", "public/header.html");
            publicInit.i18n.ChangeManual();
            getUserInfoRequest();
        }
        $("#exitSubset").bind("click", logoutRequest);
    },
    authenCheck: function(authen, uri){
        if (!authen) {
            look._AUTHEN_CHECK_FLAG ? look._AUTHEN_CHECK_FLAG = false : Look.prototype._AUTHEN_CHECK_FLAG = true;
            if (look._AUTHEN_CHECK_FLAG) {
                look.showInfo.right(look._I18N_DATA.$431/**正在重新获取权限信息…**/);
                getUserInfoRequest();
            }
            return false;
        }
        return (authen & (1 << uri)) != 0;
    },
    menuLoader: function(){
        if ($("#navPanel ul").children().length == 0) {
            //			loadPage("#nav","menu.html");
            //			$(".look_tree").looktree();
            //			getMenuCallback();
            getMenuRequest();
        }
    },
    menuSet: function(){
        if (look.getHashParam("type")) {
            $("#navPanel a").removeClass("selected").bind("click", function(){$.clearPopDiv();});
            $("#navPanel a[theme='" + (look.getHashParam("theme") ? look.getHashParam("theme") : "") + "'][dream='" + (look.getHashParam("dream") ? look.getHashParam("dream") : "") + "'][type='" + (look.getHashParam("type") ? look.getHashParam("type") : "") + "']").addClass("selected").parents("ul").attr("show", true).show().prev("li").addClass("open");
        }
    },
    //菜单设置日期&title设置
    menuDateSet: function(options){
		var defaults = {
			element: "theme",
			string: "",
			to: look.getLocalDate(),
			from: look.getLastMonthDate(look.getLocalDate())
		};
		var options = jQuery.extend(defaults, options);
        $("#navPanel a").each(function(i){
            if ($(this).attr("href") != "javascript:") {
                var hashString = $(this).attr("href");
                if (look.getStringParam(options.element, hashString) == options.string) {
                    $(this).attr("href", look.setParam([["from", options.from], ["to", options.to]], hashString));
                }
            }
        });
    },
    layout: function(){
        var wWidth = parseInt($(window).width());
        var wHeight = parseInt($(window).height());
        var hHeight = parseInt($(".header").height());
        var fHeight = parseInt($(".footer").height());
        var contentHeight = wHeight - hHeight - fHeight;
        $("#main").css({height: contentHeight});
        $("#wrapper").css({height: contentHeight - $("#topBar").outerHeight()});
        $("#nav").css("height", contentHeight + 2);
        $("#navPanel").css("height", contentHeight - 20);
    },
    setBreadcrumb: function(title){
        $("#breadcrumb .breadcrumb_cell").remove();
        var lastClass = "";
        for (var i = 0; i < title.split(",").length; i++) {
            $("#breadcrumb").append(
				'<span class="breadcrumb_cell">' +
            	'	<a href="javascript:" class="breadcrumb_link">' + title.split(",")[i] + '<span class="breadcrumb_arrow"></span>' + '</a>' +
            	'</span>');
        }
        $("#breadcrumb .breadcrumb_arrow:last").addClass("last");
    },
    inputStyle: function(){
        $(".text,textarea").live("mouseenter", function(){
            $(this).addClass("hover");
            return false;
        }).live("mouseleave", function(){
            $(this).removeClass("hover");
            return false;
        }).live("focus", function(){
            $(this).addClass("selected").select();
        }).live("blur", function(){
            $(this).removeClass("selected");
        });
    },
    inputTipStyle: function(element, label){
        $(element).bind("focus", function(){
            var tip = $(this).parent().attr("tip");
            $(this).parent().next().removeClass("color_red").text(tip);
        }).bind("blur", function(){
            if ($.trim($(this).val()) == "") {
                $(this).prev(label).show();
            } else {
                $(this).prev(label).hide();
            }
        }).live("keyup", function(){
            if ($.trim($(this).val()) == $(this).prev(label).text() || $.trim($(this).val()) == "") {
                $(this).val("");
                $(this).prev(label).show();
            } else {
                $(this).prev(label).hide();
            }
        }).each(function(){
            if ($.trim($(this).val()) != "") {
                $(this).prev(label).hide();
            } else {
                $(this).prev(label).show();
            }
            var tip = $(this).parent().attr("tip");
            $(this).parent().next().removeClass("color_red").text(tip);
        });
    },
    tabelStyle: function(zoomAble){
        $("table tbody tr").unbind("mouseenter mouseleave").bind("mouseenter", function(){
            $(this).addClass("hover");
        }).bind("mouseleave", function(){
			$(this).removeClass("hover");
		});
//		$("table tbody td").bind("mouseenter mouseleave", function(){
//			var index = $(this).index();
//			$(this).parents("tbody").children("tr").each(function(){
//				var obj = $(this).children("td").eq(index);
//				obj.toggleClass("on").siblings().removeClass("on");
//			});
//		});
        $("table tbody").each(function(){
            $(this).children("tr:odd").addClass("odd");
//			if($(this).hasClass("list") && zoomAble){publicInit.zoom($(this).find("th"), $(this));}
            if ($(this).parent().hasClass("list") && (zoomAble == undefined ? true : zoomAble)) {
                publicInit.zoom($(this).parent());
            }
        });
    },
    checkboxStyle: function(obj){
        $(obj).find(".a_as_checkbox").unbind("click").bind("click", function(){
            $(this).toggleClass("selected");
        });
    },
    i18n: {
        ChangeManual: function(){
            $("#languageChangeSubset").bind("click", function(event){
                event.stopPropagation();
                $("#languageCell").toggle();
            });
            $("body").bind("click", function(){
                $("#languageCell").hide();
            });
            $("#languageCell a").bind("click", function(event){
                event.stopPropagation();
                $.cookie("lang", $(this).attr("lang"), {
                    expires: 365,
                    path: "/"
                });
                window.location.reload();
            });
        },
        GetResource: function(){
            var lang = $.cookie("lang");
            if (!lang || lang == "") {
                $.cookie("lang", "en", {
                    expires: 365,
                    path: "/"
                });
            }
            if (!look._I18N_DATA || jQuery.isEmptyObject(look._I18N_DATA)) {
                Look.prototype._I18N_DATA = new Object();
                Look.prototype._I18N_LANGUAGE = lang;
                $.ajax({
                    url: look._I18N_RESOURCE_FOLD + "language_" + publicInit.i18n.languageMatch(lang) + ".json",
                    dataType: "json",
                    async: false,
                    success: function(back, textStatus, XMLHttpRequest){
                        look._I18N_DATA = back;
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        look.showInfo.error(textStatus);
                    }
                });
            }
        },
        Render: function(){
            if (look._I18N_DATA) {
                $("*[look-lang]").not(".rendered").each(function(){
                    var lang = $(this).attr("look-lang");
                    if (look._I18N_DATA[lang]) {
                        $(this).addClass("rendered").text(look._I18N_DATA[lang]).attr("title", look._I18N_DATA[lang]);
                    }
                });
            }
        },
        languageMatch: function(lang){
            switch (lang) {//zh-Hans, en, ko, ja, zh-Hant
                case "zh-Hans":
                    return "zh-cn";
                    break;
                case "zh-Hant":
                    return "zh-tw";
                    break;
                case "en":
                    return "en";
                    break;
                case "ko":
                    return "ko";
                    break;
                case "ja":
                    return "ja";
                    break;
                default:
                    return "en";
            }
        }
    },
    backTop: function(right){
        var backTopSubset = $('#backTopSubset');
        $("#wrapper").unbind("scroll").bind("scroll", function(){
            if ($(this).scrollTop() > 10) {
                backTopSubset.removeClass("disabled");
            } else {
                backTopSubset.addClass("disabled");
            }
        });
        
        backTopSubset.unbind("click").bind("click", function(){
            if ($(this).hasClass("disabled")) {
                return false;
            }
            $('#wrapper').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    },
    zoom: function(element){
        //		target.css("cursor", "w-resize");
        var timer = null;
        if (element == 0) {
            $(".zoom_subset").addClass("disabled");
            return false;
        } else {
            $(".zoom_subset").removeClass("disabled");
        }
        function resize(string){
            var elementWidth = parseInt(element.width());
            if (string == "in") {
                elementWidth += 50;
            } else if (string == "out") {
                if (elementWidth <= 800) {
                    clearInterval(timer);
                    return false;
                }
                elementWidth -= 50;
            } else {
                clearInterval(timer);
                elementWidth = "100%";
            }
            element.css("width", elementWidth);
        }
        $(".zoom_subset").bind("mousedown", function(){
            var type = $(this).attr("type");
            timer = setInterval(function(){
                resize(type);
            }, 50);
        }).bind("mouseup mouseleave", function(){
            clearInterval(timer);
        });
		/*
        if ($.browser.msie) {
            target.bind("mousewheel", function(e){
                var e = e || event, v = e.wheelDelta || e.detail;
                v > 0 ? resize("out") : resize("in");
                window.event.returnValue = false;
                return false;
            });
        } else {
            target.bind("DOMMouseScroll", function(event){
                event.detail < 0 ? resize("out") : resize("in");
                event.preventDefault();
            });
        }
        */
//        element.bind("dblclick", resize);
    },
	resetPublisherPanel : function(panelObj, parentObj){
		function resetLayout(){
			var panelWidth = parseFloat(panelObj.width()),
				rowNum = Math.floor(parseFloat(parentObj.width())/panelWidth),
				listLength = panelObj.length,
				maxHeight = 0;
			panelObj.css({position: "absolute"});
			for(var i = 0; i < listLength; i++){
				var topOffset = i - rowNum < 0 ? 0 : parseFloat(panelObj.eq(i - rowNum).height()) + parseFloat(panelObj.eq(i - rowNum).css("top")) + 15;
				panelObj.eq(i).css({
					left: (i % rowNum == 0 ? i % rowNum * panelWidth : i % rowNum * panelWidth + 15 * (i % rowNum)),
					top: topOffset
				});
				var prevHeight = parseFloat(panelObj.eq(i).css("top"));
				if(maxHeight < prevHeight){
					maxHeight = prevHeight + parseFloat(panelObj.eq(i).height());
				}
			}
			parentObj.css({"position": "relative","height": maxHeight});
		};
		resetLayout();
		$(window).resize(function(){
			resetLayout();
		});
	},
	menuPoper: function(items, left, top, callback){
		var html = '<div class="menu_poper">';
		for(i in items){
			html += items[i];
		}
		html += '</div>';
		$("body").append('<span style="float:left;">' + html + '</span>');
		menuPoperWidth = $(".menu_poper").width();
		$(".menu_poper").parent().remove();
		var timer = setTimeout(function(){
			$.lookPopDiv({
				left: left - menuPoperWidth,
				top: top,
				addClass: "operate_menu_panel",
				bodyClick: true,
				closer: false,
				remover: ".operate_menu_panel",
				contentHtml: html
			});
			typeof(callback) == "function" ? callback() : null;
		}, 100);
	}
}
//国家化资源加载，要最先进行加载
publicInit.i18n.GetResource();
